﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace MiniAspNetCore
{
    /// <summary>
    /// 应用管道
    /// </summary>
    public class ApplicationBuilder : IApplicationBuilder
    {
        /// <summary>
        /// 中间件集合
        /// </summary>
        private readonly List<Func<RequestDelegate, RequestDelegate>> _middlewares = new List<Func<RequestDelegate, RequestDelegate>>();

        /// <summary>
        /// 构建管道
        /// </summary>
        /// <returns></returns>
        public RequestDelegate Build()
        {
            _middlewares.Reverse();

            return context =>
            {
                //默认的最后一个中间件
                RequestDelegate next = _ => Task.CompletedTask;

                foreach (var m in _middlewares)
                {
                    //后续中间件和当前中间件构成新的中间件
                    next = m(next);
                }

                return next(context);
            };
        }

        /// <summary>
        /// 添加中间件
        /// </summary>
        /// <param name="middleware"></param>
        /// <returns></returns>
        public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _middlewares.Add(middleware);
            return this;
        }
    }
}
